package examples;

import com.oracle.coherence.patterns.security.SystemPropertyLoader;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.GSSName;
import org.ietf.jgss.Oid;

import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import java.io.FileWriter;
import java.security.PrivilegedExceptionAction;

/**
 * @author Jonathan Knight
 */
public class KrbClient implements PrivilegedExceptionAction<Object> {

    public static void main(String[] args) throws Exception {
        if (System.getProperties().containsKey(SystemPropertyLoader.MARKER_ENVIRONMENT)) {
            SystemPropertyLoader.loadProperties(null);
        }

        LoginContext lc = new LoginContext("Coherence");
        lc.login();
        Subject subject = lc.getSubject();
        Subject.doAs(subject, new KrbClient());
    }

    @Override
    public Object run() throws Exception {
        Oid krb5Oid = new Oid("1.2.840.113554.1.2.2");
        GSSManager manager = GSSManager.getInstance();
        String spn = System.getProperty("security.krb.servicename");
        GSSName serverName = manager.createName(spn, GSSName.NT_USER_NAME);
        GSSContext context = manager.createContext(serverName, krb5Oid, null, GSSContext.DEFAULT_LIFETIME);
        byte[] token = new byte[0];
        context.requestMutualAuth(false);
        context.requestCredDeleg(false);

        byte[] ticket = context.initSecContext(token, 0, token.length);
        byte[] encoded = Base64.encode(ticket).getBytes();
        
        FileWriter writer = new FileWriter("ticket.txt");
        try {
            for (byte b : encoded) {
                writer.write(b);
            }
        } finally {
            writer.close();
        }

        return null;
    }
    
}
